package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.utils.MD5Util;
import com.mmall.utils.RedisPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserMapper userMapper;

    /**
     * &#x767b;&#x9646;
     *
     * @param username
     * @param password
     * @return
     */
    public ServerResponse<User> login(String username, String password) {

        int resultCount = userMapper.checkUseraname(username);
        if (resultCount == 0) {
            return ServerResponse.retErrorMsg("用户名不存在");
        }
        //todo 密码登陆MD5
        String md5Password = MD5Util.MD5EncodeUtf8(password);

        User user = userMapper.selectLogin(username, md5Password);
        if (user == null) {
            return ServerResponse.retErrorMsg("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.retSuccess("登陆成功", user);

    }

    /**
     * 注册
     * @param user
     * @return
     */
    public ServerResponse register(User user) {
        int resultCount = userMapper.checkUseraname(user.getUsername());
        if (resultCount > 0) {
            return ServerResponse.retErrorMsg("用户名已存在");
        }

        resultCount = userMapper.checkEmail(user.getEmail());
        if (resultCount > 0) {
            return ServerResponse.retErrorMsg("email已存在");
        }
        user.setRole(Const.Role.ROLE_CUSTOMER);
        //MD5加密密码
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            return ServerResponse.retErrorMsg("注册失败");
        }

        return ServerResponse.retSuccessMsg("注册成功");
    }

    public ServerResponse checkValid(String str, String type) {
        if (StringUtils.isNotBlank(type)) {
            if (Const.USERNAME.equals(type)) {
                int resultCount = userMapper.checkUseraname(str);
                if (resultCount > 0) {
                    return ServerResponse.retErrorMsg("用户名已存在");
                }
            }
            if (Const.EMAIL.equals(type)) {
                int resultCount = userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.retErrorMsg("email已存在");
                }
            }

        } else {
            return ServerResponse.retErrorMsg("参数错误");
        }
        return ServerResponse.retSuccessMsg("校验成功");
    }

    public ServerResponse selectQuestion(String username) {
        int resultCount = userMapper.checkUseraname(username);
        if (resultCount == 0) {
            return ServerResponse.retErrorMsg("用户不存在");
        }
        String question = userMapper.selectQuestion(username);
        if (StringUtils.isNotBlank(question)) {
            return ServerResponse.retSuccessData(question);
        }
        return ServerResponse.retErrorMsg("找回密码问题失败");
    }

    public ServerResponse checkAnswer(String username, String question, String answer) {
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if (resultCount > 0) {
            //说明问题及答案是此用户的，正确的
            String forgetToken = UUID.randomUUID().toString();
//            TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
            RedisPoolUtil.setEx(Const.TOKEN_PREFIX + username, forgetToken, 60 * 60 * 12);
            return ServerResponse.retSuccessData(forgetToken);
        }
        return ServerResponse.retErrorMsg("问题的答案错误");
    }

    public ServerResponse forgetResetPassword(String username, String newPassword, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)) {
            return ServerResponse.retErrorMsg("参数错误，token为空");
        }
        int resultCount = userMapper.checkUseraname(username);
        if (resultCount == 0) {
            return ServerResponse.retErrorMsg("用户不存在");
        }
//        String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        String token = RedisPoolUtil.get(Const.TOKEN_PREFIX + username);
        if (StringUtils.isBlank(token)) {
            return ServerResponse.retErrorMsg("token无效或者已过期");
        }
        if (StringUtils.equals(token, forgetToken)) {
            String md5Password = MD5Util.MD5EncodeUtf8(newPassword);
            int rowCount = userMapper.updatePassword(username, md5Password);
            if (rowCount > 0) {
                return ServerResponse.retSuccessMsg("重置密码成功");
            }
        } else {
            return ServerResponse.retErrorMsg("token错误，请重新获取");
        }
        return ServerResponse.retErrorMsg("重置密码失败");
    }
    public ServerResponse resetPassword(User user, String oldPassword, String newPassword) {
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(oldPassword), user.getId());
        if (resultCount == 0) {
            return ServerResponse.retErrorMsg("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(newPassword));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServerResponse.retSuccessMsg("密码重置成功");
        }
        return ServerResponse.retErrorMsg("密码重置失败");
    }
    public ServerResponse updateInformation(User user) {
        //email也要进行校验，校验新的email是不是已经存在,并且不是当前用户的
        int resultCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (resultCount > 0) {
            return ServerResponse.retErrorMsg("email已经存在，请更换Email");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount > 0) {
            return ServerResponse.retSuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.retErrorMsg("更新个人信息失败");
    }

    public ServerResponse getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return ServerResponse.retErrorMsg("未找到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.retSuccessData(user);
    }

    /**校验是否是管理员
     * @param user
     * @return
     */
    public ServerResponse checkAdminRole(User user){
        if(user != null && user.getRole().intValue() == Const.Role.ROLE_ADMIN){
            return ServerResponse.retSuccess();
        }
        return ServerResponse.retError();
    }
}